package com.house.generator;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.house.framework.controller.BaseController;
import com.house.framework.entity.BaseEntity;
import com.house.framework.mapper.MapperBase;
import com.house.framework.service.impl.ServiceBaseImpl;

import java.io.*;
import java.util.*;

public class CodeGenerator {

    public static final String PARENT_PACKAGE = "com.house.business";

    public static final String ENTITY_PACKAGE = "entity";

    public static final Boolean GET_ALL_TABLE = false;

    /**
     * 需要生成的表
     * @return
     */
    public static List<String> getTables() {
        if(GET_ALL_TABLE) {
            return ConnectionUtils.getAllTable();
        }
        return ConnectionUtils.getTableListWithPrefix(new String[]{
                "t_fault",
                "t_housing_resources_info",
                "t_leasing_information",
                "t_message",
                "t_notice",
                "t_reservation"
        });
    }

    public static void main(String[] args) {
        try {
            FastAutoGenerator.create("jdbc:mysql://rm-cn-9lb37ei3k001e37o.rwlb.cn-chengdu.rds.aliyuncs.com:3306/house_test?useUnicode=true&useSSL=false&characterEncoding=utf-8&serverTimezone=UTC%2B8&allowPublicKeyRetrieval=true",
                    "mysqlroot","MySQLroot@")
                    .globalConfig(builder -> {
                        builder.author("zhoukeu")               //作者
                                .outputDir(System.getProperty("user.dir")+"/WebServiceApi/src/main/java")    //输出路径(写到java目录)
                                .enableSwagger()           //开启swagger
                                .commentDate("yyyy-MM-dd")
                                .fileOverride(); //开启覆盖之前生成的文件
                    })
                    .packageConfig(builder -> {
                        builder.parent(PARENT_PACKAGE)
                                //.moduleName("api")
                                .entity("entity")
                                .service("service")
                                .serviceImpl("service.impl")
                                .controller("controller")
                                .mapper("mapper")
                                .xml("mapper")
                                .pathInfo(Collections.singletonMap(OutputFile.mapperXml,System.getProperty("user.dir")+"/WebServiceApi/src/main/resources/mapper/business"));
                    })
                    .strategyConfig(builder -> {
                        //builder.addInclude(tables)
                        builder.addInclude(getTables())//.addExclude("T_SYS_USERCONFIGSORTMX","T_Sys_Department","T_Sys_GlobalConfig","T_Sys_LoginSession","T_Sys_Log","T_Sys_MenuAuthorize","T_Sys_Menus","T_Sys_Message", "T_Sys_OperationLogDetail","T_Sys_OperationLog","T_Sys_Position","T_Sys_RoleRelation","T_Sys_Role","T_SYS_SYSTEMSMS","T_SYS_UNITEXTEND","T_Sys_Unit", "T_SYS_USERCONFIGSORT","T_Sys_UserExtend","T_Sys_User","TB_PL_UNIT", "V_Sys_User", "V_Sys_UserList", "veiw_System_UserConfigSortInfo")
                                .addTablePrefix("T_")
                                .addFieldPrefix("F_")
                                .entityBuilder()
                                .superClass(BaseEntity.class)
                                .enableLombok()
                                .logicDeleteColumnName("F_IsDeleted")
                                .enableTableFieldAnnotation()
                                .serviceBuilder()
                                .formatServiceFileName("%sService")
                                .superServiceImplClass(ServiceBaseImpl.class)
                                .formatServiceImplFileName("%sServiceImpl")
                                .controllerBuilder()
                                .enableHyphenStyle()
                                .superClass(BaseController.class)
                                .formatFileName("%sController")
                                .enableRestStyle()
                                .mapperBuilder()
                                .superClass(MapperBase.class)
                                .formatMapperFileName("%sMapper")
                                .enableMapperAnnotation()
                                .formatXmlFileName("%sMapper").enableBaseResultMap().enableBaseColumnList();
                    })
                    .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板，默认的是Velocity引擎模板
                    .injectionConfig(builder -> {
                        builder.customMap(new HashMap<String,Object>(){{
                            put("util",new CodeUtils());//代码处理工具类
                        }});
                    })
                    .execute();
            generateVO();
        }catch (Exception e){
            System.out.println(e);
        }
    }

    private static void generateVO() {
        String outputDir = System.getProperty("user.dir")+"/WebServiceApi/src/main/java";
        String voPackage = outputDir + "/" + PARENT_PACKAGE.replaceAll("\\.","/") + "/" + "vo";
        String entityPackage = outputDir + "/" + PARENT_PACKAGE.replaceAll("\\.","/") + "/" + "entity";
        File voPackageFile = new File(voPackage);
        if(!voPackageFile.exists()) {
            voPackageFile.mkdirs();
        }
        File entityPackageFile = new File(entityPackage);
        File[] entity = entityPackageFile.listFiles();
        for (File file : entity) {
            try {
                copyEntityFile(file,voPackage);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static void copyEntityFile(File file, String voPackage) throws Exception{
        if(file.isDirectory()) {
            File[] entity = file.listFiles();
            for (File f : entity) {
                copyEntityFile(f,voPackage);
            }
        } else {
            String entityName = file.getName();
            String voName = entityName.replaceAll("\\.","Vo.");
            File entityVoFile = new File(voPackage + "/" + voName);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
            if(entityVoFile.exists()) {
                entityVoFile.delete();
                entityVoFile.createNewFile();
            }
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                line = line.replaceAll("entity;","vo;");
                line = line.replaceAll(entityName.substring(0,entityName.indexOf(".")),voName.substring(0,voName.indexOf(".")));
                if(line.trim().startsWith("}")) {
                    writeVoFile(entityVoFile,"    @ApiModelProperty(\"分页页码\")\n" +
                            "    @TableField(exist = false)\n" +
                            "    private Integer pageIndex;\n" +
                            "\n" +
                            "    @ApiModelProperty(\"每页记录条数\")\n" +
                            "    @TableField(exist = false)\n" +
                            "    private Integer pageSize;");
                }
                writeVoFile(entityVoFile,line);
            }
        }
    }
    public static void writeVoFile(File file,String text) throws Exception{
        FileWriter fw = new FileWriter(file,true);
        PrintWriter pw = new PrintWriter(fw);
        pw.println(text);
        pw.flush();
        fw.flush();
        pw.close();
        fw.close();
    }

    // 处理 all 情况
    protected static List<String> getTables(String tables) {
        return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
    }
}
